package com.xj.api.bussiness.UploadFile.web;

import io.swagger.annotations.Api;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import okhttp3.OkHttpClient;
import okhttp3.Request;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import com.xj.api.base.web.BaseController;
import com.xj.common.base.common.bean.AbstractBean;
import com.xj.common.base.common.util.IdGen;
/**
 * <p>
 *     照片上传控制器
 * </p>
 *
 * @author zhaohai
 * @since 2018-01-12
 */
@RestController
@CrossOrigin("*")
@Api(value = "FileController", description = "文件上传api")
@RequestMapping(value = "/upload")
public class QiniuUploadController extends BaseController {
	
	    @Value("${qiniu.accessKey}")
	    private String accessKey;
	    @Value("${qiniu.secretKey}")
	    private String secretKey;
	    @Value("${qiniu.bucket}")
	    private String bucket;
	    @Value("${qiniu.path}")
	    private String path;
	 
	/**
	 * 单文件上传
	 * 
	 * @param req
	 * @param multiReq
	 * @throws Exception 
	 */
	@RequestMapping(value = "/uploadFile2Qiniu", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFile2Qiniu(HttpServletRequest req, MultipartHttpServletRequest multiReq) throws Exception {
		FileInputStream inputStream = null;
		String imageUrl ="";
		try {
			    inputStream = (FileInputStream) multiReq.getFile("file").getInputStream();
			    imageUrl = uploadQNImg(inputStream,IdGen.getImageNum()); // KeyUtil.genUniqueKey()生成图片的随机名
		        return imageUrl;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return StringUtils.replace(imageUrl,"\\","/");
	}
	
	
	/**
	 * OSS多文件上传
	 * 
	 * @param request
	 */
	@RequestMapping(value = "/areaFiles2Qiniu", method = RequestMethod.POST)
	@ResponseBody
	public String areaFiles(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		List<Object> paths = Lists.newArrayList();
		FileInputStream inputStream = null;
		String imageUrl ="";
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					 inputStream = (FileInputStream) file.getInputStream();
					 imageUrl = uploadQNImg(inputStream,IdGen.getImageNum()); // KeyUtil.genUniqueKey()生成图片的随机名
					 paths.add(imageUrl);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (stream != null) {
							stream.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		JSONObject json = new JSONObject();
		json.put("errno", 0);
		JSONArray jsonarray = new JSONArray(paths);  
		json.put("data", jsonarray);
		return json.toString();
//		return Collections3.convertToString(paths, ",").replaceAll(File.separator, "/");
	}
	
	/**
     * 将图片上传到七牛云
     */
    private String uploadQNImg(FileInputStream file, String key) {
        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成上传凭证，然后准备上传

        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(file, key, upToken, null, null);
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                String returnPath = path + "/" + putRet.key;
                return returnPath;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    /**
	 * 删除文件
	 * 
	 * @param request
	 */
	@RequestMapping(value = "/deleteQiniu", method = RequestMethod.POST)
	@ResponseBody
	public AbstractBean deleteQiniu(@RequestParam String path) {
		//获取Auth对象
        Auth auth = Auth.create(accessKey, secretKey);
        //指定需要删除的空间和文件，格式为： <bucket>:<key>
        //通过安全base64编码方式进行编码处理
        String encodedEntryURI = UrlSafeBase64.encodeToString(path);
        //指定接口
        String target = "/delete/" + encodedEntryURI + "\n";
        //获取token，即操作凭证
        String access_token = auth.sign(target);
        //指定好请求的delete接口地址
        String url = "http://pa1j0e97s.bkt.clouddn.com/delete/" + encodedEntryURI;

        //通过Okhttp jar 包封装的对象 发起网络请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "QBox " + access_token).build();
        okhttp3.Response re = null;
        try {
            re = client.newCall(request).execute();
            if (re.isSuccessful() == true) {
               return json(re.code());
            } else {
               return json(re.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		return null;
    }
}
